#!/usr/bin/python
# -*- coding: utf-8 -*-
import file_handle
import urllib
import sys
import html_data
from bs4 import BeautifulSoup
import re
import novel_info

_url_address = r'https://www.baidu.com/s?%s&ct=2097152&si=www.bxwx9.org&sts=www.bxwx9.org'


def find_by_baidu(novel_name=''):
    if len(novel_name) == 0:
        print('请输入小说名称：')
    else:
        name = unicode(novel_name, "utf-8")
        name = name.encode('gb2312')
        q = urllib.urlencode({'wd': name})
        add = _url_address % q
        add = add.replace('https', 'http')
        html_context = html_data.get_html(add)
        soup = BeautifulSoup(html_context, 'html.parser')
        search_tag = soup.find_all('h3', attrs={'class': 't'})
        novel_address = search_tag[0].contents[0].get('href')
        novel_address_response = html_data.get_response(novel_address)
        novel_rel_address = novel_address_response.geturl()
        novel_rel_address_items = novel_rel_address.split('/')
        novel_rel_address_last = novel_rel_address_items[len(novel_rel_address_items) - 1]
        novel_address_html = novel_address_response.read()
        novel_address_html = unicode(novel_address_html, 'GBK').encode('UTF-8')
        novel_dir_soup = BeautifulSoup(novel_address_html, 'html.parser')
        print('书名:' + novel_name)
        novel_titles = novel_dir_soup.find_all('dd')
        _href_re = r'<a href="(\S+)">(.+)</a>'
        novel_chapters = []
        for i in novel_titles:
            try:
                context = str(i.contents[0]).strip()
                m = re.match(_href_re, context)
                chapter_name = m.group(2)
                chapter_url = novel_rel_address.replace(novel_rel_address_last, m.group(1))
                novel_chapter = novel_info.Novel_chapter(chapter_url, chapter_name)
                novel_chapters.append(novel_chapter)
            except UnicodeEncodeError:
                pass
        chapter_num = len(novel_chapters)
        count = 0
        while chapter_num >= (count + 4):
            tmp = novel_chapters[count]
            novel_chapters[count] = novel_chapters[count + 1]
            novel_chapters[count + 1] = novel_chapters[count + 3]
            novel_chapters[count + 3] = tmp
            count += 4
        novel_data = novel_info.Novel(novel_name, novel_rel_address, novel_chapters, novel_name + '.txt')
        novel_data.start()


if __name__ == '__main__':
    args = sys.argv
    # find_by_baidu('最强天命系统')
    if len(args) > 1:
        find_by_baidu(args[1])
